<template>
  <div class="page-table">
    <div class="page-filter">
      <div class="query">
        <el-form ref="form" :inline="true" size="small">
          <el-form-item>
            <el-date-picker
                v-model="searchQuery.beginSearchTime"
                type="datetime"
                style="width: 170px"
                value-format="timestamp" format="yyyy-MM-dd HH:mm"
                placeholder="开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-date-picker
                v-model="searchQuery.endSearchTime"
                type="datetime"
                style="width: 170px"
                value-format="timestamp" format="yyyy-MM-dd HH:mm"
                placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.orderSubNo" style="width: 120px;" placeholder="订单号" clearable/>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.carName" style="width: 120px;" placeholder="车辆名称" clearable/>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.vin" style="width: 120px;" placeholder="车牌/车架号" clearable/>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.createUserName" style="width: 120px;" placeholder="制单人" clearable/>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.linkmanName" style="width: 120px;" placeholder="委托联系人" clearable/>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchQuery.linkmanPhone" style="width: 120px;" placeholder="联系电话" clearable/>
          </el-form-item>

          <el-button type="primary" plain size="small" @click="queryList()">查询
          </el-button>
        </el-form>
      </div>
      <div class="op">
        <el-button size="mini" :disabled="isEdit"
                   @click="$router.push({path: '/transport/assign', query: {id: orderId}})">修改
        </el-button>
        <el-button size="mini" :disabled="isEdit"
                   @click="cancelShipping">取消发运
        </el-button>
        <el-button size="mini" :disabled="!searchQuery.beginSearchTime && !searchQuery.endSearchTime" :loading="orderDownloading" @click="exportExcel">导出</el-button>
      </div>
    </div>
    <div class="box-style">
      <div class="top">
        <ad-table
          :style="drawer ? 'marginBottom:200px': 'marginBottom:0px'"
          :data="assignRecordList" u-table @sort-change="assignRecordSortInitList"
                  :data-changes-scroll-top="assignRecordIsScrollTop"
                  v-loading="assignRecordInitLoading" @table-body-scroll="assignRecordGetMoreList"
                  :searchQuery="assignRecordSearchQuery" @search="assignRecordGetInitList"
                  @filter-change="assignRecordFilterInitList"
          :height="drawer === true ? tableHeight-300 :tableHeight" @cell-click="cellClick">
          <!--          <ad-table-column type="selection" ctype="selection" fixed/>-->
          <ad-table-column label="序号" type="index" ctype="index" fixed/>
          <ad-table-column label="运单号" prop="transportNo" searchable>
            <!--                                    <template slot-scope="scope">-->
            <!--                                      <el-input size="mini" v-model="scope.row.orderSubNo"></el-input>-->
            <!--                                    </template>-->
          </ad-table-column>
          <ad-table-column label="运单创建人" prop="createUserName" w="4c2f" searchable sortable/>
          <ad-table-column label="运单创建时间" prop="createTime" width="130" ctype="datetime" sortable/>
          <ad-table-column label="路线" prop="line" w="4c2f" ctype="line" filterable/>
          <ad-table-column label="承运单位" prop="companyName" w="4c2f" filterable/>
          <ad-table-column label="运输方式" prop="transportType" dictName="transport_way" filterable w="4c1f"/>
          <ad-table-column label="结算人" prop="settlementName" w="3c2f" searchable/>
          <ad-table-column label="结算电话" prop="settlementPhone" ctype="phone-2f" searchable/>
          <ad-table-column label="司机姓名" prop="driverName" w="4c2f" searchable/>
          <ad-table-column label="司机电话" prop="driverPhone" ctype="phone-2f" searchable/>
          <ad-table-column label="板车牌号" prop="licensePlateNumber" w="4c2f"/>
          <ad-table-column label="车厢号" prop="compartmentNo" w="4c2f" searchable/>
          <ad-table-column label="票号" prop="ticketNo" w="4c2f" searchable/>
          <ad-table-column label="应付运费" prop="driverFee" w="4c2f" sortable/>
          <ad-table-column label="代收金额" prop="collectionFee" w="4c2f" sortable/>
          <ad-table-column label="欠返运费" prop="backReturnFee" w="4c2f" sortable/>
          <ad-table-column width="auto"/>
        </ad-table>
      </div>

<!--      底部弹框-->
<!--      <el-drawer-->
<!--        size="35%"-->
<!--        :visible.sync="drawer"-->
<!--        direction="btt"-->
<!--        :with-header="false">-->
      <div id="bottom" v-show="drawer" class="bottom" style="min-height: 290px">
        <div class="title-bar">
          <h2>运单号 : {{transportNo}}</h2>
          <el-button size="mini" type="info" plain @click="drawer = false" >取消</el-button>
        </div>
        <div class="content">
          <div class="right" :style="{'border-left':'none'}">
            <ad-table class="editTable" :data="tableData" u-table excess-rows="50"
                      :height="bottomTabHeight" :span-method="objectSpanMethod">
              <ad-table-column label="操作" prop="levelId" width="120">
                <template slot-scope="{row}">
                  <slot :row="row">
                    <span v-if="row.reserved==1">留板信息</span>
                    <span class="el-link--inner" v-else-if="!row.levelFileUrl" @click="createWaybill(row)">生成发运单</span>
                    <a class="el-link--inner" v-else :href="row.levelFileUrl" target="_blank">查看发运单</a>
                    <a class="el-link--inner" style="margin-left: 10px" @click="exportPlan(row.levelId)">导出</a>
                  </slot>
                </template>
              </ad-table-column>
              <ad-table-column label="路线" prop="line" ctype="line" w="4c2f"/>
              <!--              <ad-table-column label="结算方式" prop="levelSettlementType" dictName="settlement_type" w="3c2f"/>-->
              <ad-table-column label="发运人" prop="createUserName" w="3c2f"/>
              <ad-table-column label="发运时间" prop="createTime" ctype="datetime" w="1f"/>
              <ad-table-column label="交付方式" prop="levelType" dictName="delivery_type" w="3c2f"/>
              <ad-table-column label="接车联系人" prop="levelReceiveUser" w="3c2f"/>
              <ad-table-column label="接车联系人电话" prop="levelReceivePhone" ctype="phone-2f"/>
              <ad-table-column label="接车地址" prop="levelReceiveAddress" ctype="address-2f"/>
              <ad-table-column label="订单编号" prop="orderSubNo" ctype="orderNo" w="3c2f"/>
              <ad-table-column label="订单状态" prop="orderStatus" dictName="order_status" w="3c2f"/>
              <ad-table-column label="出发地" prop="orderStartCode" ctype="city"/>
              <ad-table-column label="目的地" prop="orderDestinationCode" ctype="city"/>
              <ad-table-column label="车辆名称" prop="orderCarName" w="4c2f"/>
              <ad-table-column label="车架号" prop="orderVin" ctype="vin-2f"/>
              <ad-table-column label="制单人" prop="orderCreateUserName" w="3c2f"/>
              <ad-table-column label="收货人" prop="orderConsigneeName" w="3c2f"/>
              <ad-table-column label="联系电话" prop="orderConsigneePhone" ctype="phone-2f"/>
              <ad-table-column label="承运费用" prop="cost" w="3c2f"/>
              <ad-table-column label="到付金额" prop="orderDeliveryPayFee" w="3c2f"/>
              <ad-table-column label="是否代收" prop="hasCollection" w="3c2f">
                <template slot-scope="{row}">
                  <slot :row="row">
                    <span v-if="row.hasCollection==1">是</span>
                    <span v-else-if="row.hasCollection==0">否</span>
                    <span v-else>-</span>
                  </slot>
                </template>
              </ad-table-column>
            </ad-table>
          </div>
        </div>
      </div>
<!--      </el-drawer>-->

    </div>

  </div>
</template>

<script>
  import AdSuggestion from '@/components/AdSuggestion'
  import AdTable from '@/components/AdTable'
  import AdTableColumn from '@/components/AdTable/AdTableColumn'
  import adTable from '@/mixins/adTable'
  import Value from '@/components/AdValue'
  import api, {get as assignRecordApiGetList} from '@/api/transportop/assignRecord';
  import AdUpload from '@/components/AdUpload'
  import noData from '@/assets/404_images/nodata.png';
  import SettlerManage from '@/components/SettlerManage';
  import DriverManage from '@/components/DriverManage'
  import AdStatusSelect from '@/components/AdStatusSelect'
  import AdStatusSelectNoclear from '@/components/AdStatusSelect/noClear'
  import AdCitySelect from '@/components/AdCitySelect'
  import {
    getCompanyList as getSuggestCompanyList
  } from '@/api/suggestion'
  import apiUser from '@/api/system/user';
  import {parseStatus} from '@/utils/code';
  import {download} from '@/api/data';
  import {downloadFile} from '@/utils/index'

  export default {
    name: 'transportop-assignRecord',
    components: {
      AdTable,
      AdTableColumn,
      AdSuggestion,
      Value,
      AdUpload,
      AdStatusSelect,
      AdStatusSelectNoclear,
      SettlerManage,
      AdCitySelect,
      DriverManage
    },
    dicts: ['order_status', 'pickcar_status', "verifycar_status", "pick_stock_status", "takecar_type", "settlement_type", "transport_type", "delivery_type","transport_way"],
    mixins: [adTable([
      {name: 'assignRecord'},
    ])],
    data() {
      return {
        orderDownloading: false,
        drawer: false,
        isInspect: false,
        isEdit: true,
        transportNo: '-',
        orderId: null,
        noData,
        tableData: [],
        siteArray: [],
        receiveUserArray: [
          []
        ],
        waybillTableData: [],
        roadPoint: [
          {
            type: 1,
            siteId: null,
            receiveUser: null,
            receivePhone: null,
            receiveAddress: null,
            settlementType: null,
            transferCityCode: null,
            bottomTableData: [],
          }
        ],
        isWaybill: false,
        rightHeight: 'calc(36vh - 37px)',
        searchQuery: {
          beginSearchTime: null,
          endSearchTime: null,
          siteId: null
        },
        editableTabsValue: '1',
        editableTabs: [
          {
            title: '途径点1',
            name: '1',
          }
        ],
        tabIndex: 1,
        tableHeight: 440,
        bottomTabHeight: 300,

        saveForm: {
          transportNo: null,
          type: null,
          company: null,
          collectionFee: null,
          backReturnFee: null,
          companyId: null,
          pickCarFee: null,
          settlementId: null,
          settlementName: null,
          settlementPhone: null,
          driverId: null,
          driverName: null,
          driverPhone: null,
          driverCardNumber: null,
          licensePlateNumber: null
        },
        inspectForm: {
          specification: undefined,
          towHook: undefined,
          ashtray: undefined,
          toolkit: undefined,
          antenna: undefined,
          key: undefined,
          warningSign: undefined,
          licensePlateFrame: undefined,
          aidPacket: undefined,
          footPad: undefined,
          airPump: undefined,
          cigarLighter: undefined,
          spareTire: undefined,
          jack: undefined,
          bellCover: undefined,
          vin: undefined,
          km: undefined,
          remark: undefined,
        },
        rules: {
          // company: [
          //   {required: true, message: '必选', trigger: 'blur'},
          // ],
          // settlementName: [
          //   {required: true, message: '必选', trigger: 'blur'},
          // ],
          // settlementType: {required: true, message: '必选', trigger: 'blur'},
          // settlementPhone: [
          //   {required: true, message: '必选', trigger: 'blur'},
          // ]
        },
        inspectRules: {
          vin: [
            {required: true, message: '必填', trigger: 'blur'},
          ],
          km: [
            {required: true, message: '必填', trigger: 'blur'},
          ]
        },

        data: {},
        dialogVisible: false,
        dialogSettlerVisible: false,
        dialogDriverVisible: false,
      }
    },
    created() {
      let self = this;
      self.assignRecordGetInitList()
      setTimeout(function () {
        // self.tableHeight = document.documentElement.clientHeight - document.getElementById('bottom').offsetHeight - 160;
        self.tableHeight = document.documentElement.clientHeight  - 160;
        self.bottomTabHeight = document.getElementById('bottom').offsetHeight - 35;
      })

      if (this.detectZoom() == 100) {
        this.rightHeight = 'calc(36vh - 37px)'
      }
      if (this.detectZoom() == 125) {
        this.rightHeight = 'calc(36vh - 17px)'
      }
    },
    methods: {
      assignRecordApiGetList, parseStatus, getSuggestCompanyList,
      objectSpanMethod({row, column, rowIndex, columnIndex}) {
        let self = this;
        if (column.property === 'levelId') {
          if (rowIndex === 0 || row.levelId != self.tableData[rowIndex - 1].levelId) {
            let rowspan = 0;
            self.tableData.forEach(element => {
              if (element.levelId === row.levelId) {
                rowspan++;
              }
            });
            return [rowspan, 1];
          } else {
            return [0, 0];
          }
        }
      },
      //导出
      exportPlan: function (id) {
        let self = this;
        download(`api/transport/export/` + id, null).then(res => {
          downloadFile(res.data, res.headers.downloadFileName, 'xlsx')
        })
      },
      createWaybill: function (row) {
        let self = this;
        api.transportLevel({
          transportLevelId: row.levelId
        }).then(res => {
          if (res.code == 0) {
            self.$confirm('是否查看发运单?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              window.open(res.data)
            }).catch(() => {

            });
            self.queryList();
            self.tableData = [];
          } else {
            self.$notify({
              title: '生成发运单',
              message: res.msg,
              position: 'bottom-right',
              type: 'error'
            });
          }
        })
      },
      detectZoom: function () {
        let ratio = 0,
          screen = window.screen,
          ua = navigator.userAgent.toLowerCase();

        if (window.devicePixelRatio !== undefined) {
          ratio = window.devicePixelRatio;
        } else if (~ua.indexOf('msie')) {
          if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
          }
        } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
          ratio = window.outerWidth / window.innerWidth;
        }

        if (ratio) {
          ratio = Math.round(ratio * 100);
        }
        return ratio;
      },
      //查询
      queryList: function () {
        let self = this;
        self.isWaybill = false;
        self.roadPoint = [
          {
            type: 1,
            siteId: null,
            receiveUser: null,
            receivePhone: null,
            receiveAddress: null,
            settlementType: null,
            transferCityCode: null,
            bottomTableData: [],
          }
        ];
        self.clearFrom();
        self.editableTabsValue = '1';
        self.editableTabs = [
          {
            title: '途径点1',
            name: '1',
          }
        ];
        self.tabIndex = 1;
        self.assignRecordGetInitList()
      },
      //取消发运
      cancelShipping: function () {
        let self = this;
        self.$confirm('是否确定取消发运?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.cancelShipping(self.data.id).then(res => {
            if (res.code == 0) {
              self.$notify({
                title: '取消发运',
                message: res.msg,
                position: 'bottom-right',
                type: 'success'
              });
              self.queryList();
              self.transportNo = '-';
              self.tableData = [];
            } else {
              self.$notify({
                title: '取消发运',
                message: res.msg,
                position: 'bottom-right',
                type: 'error'
              });
            }
          })
        }).catch(() => {
        });
      },
      cellClick(row, column, event) {
        let self = this;
        self.drawer = true;
        self.isEdit = false;
        switch (column.property) {
          default:
            self.transportNo = row._row ? row._row.transportNo : row.transportNo;
            self.orderId = row.id;
            api.transportExpand(row.id).then(res => {
              res.data.forEach(d => {
                d.line = d.levelStartCode + ',' + d.levelDestinationCode;
              })
              self.tableData = res.data;
            })
            self.data = row;
        }
      },
      removeLink() {
        let self = this;
        self.saveForm.companyId = null
        self.saveForm.company = null
        self.saveForm.settlementId = null
        self.saveForm.settlementName = null
        self.saveForm.settlementPhone = undefined
      },
      //清空
      clearFrom: function () {
        let self = this;
        self.removeLink();
        self.saveForm.pickCarFee = null;
        self.saveForm.driverName = null;
        self.saveForm.driverPhone = null;
        self.saveForm.driverCardNumber = null;
        self.saveForm.licensePlateNumber = null
        self.saveForm.collectionFee = null;
        self.saveForm.type = null;
        self.saveForm.transportNo = null;
        self.saveForm.backReturnFee = null;
        self.saveForm.backReturnFee = null;
      },
      exportExcel() {
        this.orderDownloading = true
        const loading = this.$loading({lock: true, text: '正在下载，请稍等...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'})
        download('/api/transport/finish/export', {...this.searchQuery}).then(result => {
          downloadFile(result.data, result.headers.downloadFileName, 'xlsx')
          loading.close()
        }).finally(() => {
          loading.close()
          this.orderDownloading = false
        })
      },
    }

  }
</script>

<style lang="scss" scoped>
  .page-table {
    display: flex;
    flex: 1;
    flex-direction: column;

    .box-style {
      display: flex;
      flex: 1;
      border: 1px solid #e3e3e3;
      flex-direction: column;
    }

    .top {
      display: flex;
      flex: 1;
      border-bottom: 1px solid #4da7fa;
      flex-direction: column;

      &:after {
        content: '';
        display: block;
        height: 4px;
        background: #4da7fa;
        opacity: 0.2;
      }

      .table-wrapper {
        flex: 1;
      }

      .table {
        flex: 1;
      }
    }

    .bottom {
      //display: flex;
      position: fixed;
      bottom: 0;
      height: 36vh;
      width: 98vw;
      z-index: 999;
      background-color: #fff;
      //flex-direction: column;

      .title-bar {
        display: flex;
        justify-content: space-between;
        line-height: 34px;
        background: #f5f5f5;
        border-bottom: 1px solid #e3e3e3;
        padding-left: 10px;
        flex-shrink: 0;

        .op {
          margin-left: auto;
          margin-right: 12px;
        }
      }

      .content {
        display: flex;
        flex: 1;
        overflow: hidden;

        .left {
          display: flex;

          &:after {
            content: '';
            display: block;
            width: 3px;
            background: #4da7fa;
            opacity: 0.2;
          }
        }

        .middle {
          display: flex;
        }

        .line {
          border-right: 1px #e3e3e3 solid;
        }

        .right {
          flex: 1;
          overflow: hidden;

          .table-wrapper {
            height: 100%;
          }
        }

        .form-wrapper {
          display: flex;
          flex: 1;
          flex-direction: column;
          width: 18vw;

          h3 {
            height: 35px;
            box-sizing: border-box;
          }

          .form-content {
            padding: 10px 10px 0 10px;
            box-sizing: border-box;
            overflow-y: auto;

            .el-form-item {
              margin-bottom: 10px;
            }
          }
        }
      }
    }

    .bottom {
      & > .title-bar {
        padding-left: 16px;
        border-bottom: 1px solid #bdd0e3;
        background: #f5f5f5;
        align-items: center;
      }

      h2 {
        font-size: 12px;
      }

      h3 {
        padding-left: 10px;
        border-bottom: 1px solid #e3e3e3;
        background: #f5f5f5;
        line-height: 30px;
        font-size: 12px;
      }

      //.left h3 { border-right: 1px solid #e3e3e3; }
      //.middle h3 { border-left: 1px solid #e3e3e3; }
      .right {
        border-left: 1px solid #e3e3e3;
      }
    }
  }
</style>